﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace AudioRecorder
{
    public class RecordingAudio
    {


        public RecordingAudio()
        {

        }

        static int sum = 0;
        static Timer timer;

        /// <summary>
        /// 获取当前是否是正在录制状态
        /// </summary>
        public static bool IsRecordingAudio { get; private set; }


        [DllImport("winmm.dll", EntryPoint = "mciSendString", CharSet = CharSet.Auto)]
        public static extern int mciSendString(
         string lpstrCommand,
         string lpstrReturnString,
         int uReturnLength,
         int hwndCallback
        );

        /// <summary>
        /// 开始录制
        /// </summary>
        public  void Start()
        {
            mciSendString("set wave bitpersample 16", "", 0, 0);
            mciSendString("set wave samplespersec 22050", "", 0, 0);
            mciSendString("set wave channels 1", "", 0, 0);
            mciSendString("set wave format tag pcm", "", 0, 0);
            mciSendString("open new type WAVEAudio alias movie", "", 0, 0);
            mciSendString("record movie", "", 0, 0);

            timer = new Timer(200);
            timer.Elapsed += timer_Tick;
            sum = 0;
            timer.Enabled = true;

            IsRecordingAudio = true;
        }

        private static void timer_Tick(object sender, ElapsedEventArgs e)
        {
            sum++;
        }
        public  string src { get; set; }
        public string fileName { get; set; }
        /// <summary>
        /// 停止录制，返回录制时间(进1原则)
        /// </summary>
        /// <returns></returns>
        public  int Stop()
        {
            fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".wav";
            src = "resource/" + fileName;
            mciSendString("stop movie", "", 0, 0);
            mciSendString("save movie " + src, "", 0, 0);
            mciSendString("close movie", "", 0, 0);

            IsRecordingAudio = false;
            timer.Enabled = false;
            timer.Dispose();
            int s = sum * 200;
            return s % 1000 == 0 ? s / 1000 : s / 1000 + 1;///进1原则
        }

    }
}
